package com.ternnetwork.batch.writer;

import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.file.ResourceAwareItemWriterItemStream;
import org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor;
import org.springframework.batch.item.file.transform.DelimitedLineAggregator;
import org.springframework.batch.item.file.transform.FieldExtractor;
import org.springframework.batch.item.file.transform.LineAggregator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;

import com.ternnetwork.batch.item.support.ExtendedMultiResourceItemWriter;
import com.ternnetwork.batch.model.TestUser;



/**
 * 多文件写入器
 * @author xuwenfeng
 *
 */
@Configuration
public class TestUserMultiResourceItemWriterConfiguration {
	
	
	
	
	
	 /**
	  * 获取多文件写入器
	  * @return
	  */
	 @Bean("testUserMultiResourceItemWriter")
	 public ItemWriter<TestUser> getMultiResourceItemWriter() {
		 
		 ExtendedMultiResourceItemWriter<TestUser> extendedMultiResourceItemWriter=new ExtendedMultiResourceItemWriter<TestUser>();
		 
		 //文件名输出路径
		 FileSystemResource fileUrlResource = new FileSystemResource("/Users/xuwenfeng/Documents/ws/avocado-cloud-parent/avocado-cloud-batch/src/main/resources/test-data/user_ouput.csv");
		
		 extendedMultiResourceItemWriter.setResource(fileUrlResource);
	
		 //设置每个文件数据条数，多出的条数会写多个文件，不设置只会写一个文件 和step中的chunk有关
		 extendedMultiResourceItemWriter.setItemCountLimitPerResource(2);
		 
		 extendedMultiResourceItemWriter.setDelegate(getFlatFileItemWriter());
		 
		 return extendedMultiResourceItemWriter;
		 
	 }
	
	
	
	
	
	
	/**
	 * 获取文本文件写入器
	 * @return
	 */
	public ResourceAwareItemWriterItemStream<TestUser> getFlatFileItemWriter() {
		
		FlatFileItemWriter<TestUser> flatFileItemWriter=new FlatFileItemWriter<TestUser>();
		
		flatFileItemWriter.setLineAggregator(getLineAggregator());
		
		flatFileItemWriter.setAppendAllowed(false);
		
		return flatFileItemWriter;
	}
	
	
	/**
	 * 获取行聚合器
	 * @return
	 */
	public LineAggregator<TestUser> getLineAggregator() {
	
	  DelimitedLineAggregator<TestUser> delimitedLineAggregator=new DelimitedLineAggregator<TestUser>();
	
	  //设置分割符 
	  delimitedLineAggregator.setDelimiter(",");
	  
	  //设置字段抽取器
	  delimitedLineAggregator.setFieldExtractor(getFieldExtractor());
	  
	  return delimitedLineAggregator;
     
   }
	
	
	/**
	 * 获取字段抽取器
	 * @return
	 */
	public FieldExtractor<TestUser> getFieldExtractor(){
		
		BeanWrapperFieldExtractor<TestUser> beanWrapperFieldExtractor=new BeanWrapperFieldExtractor<TestUser>();
		
		beanWrapperFieldExtractor.setNames(new String[]{"id","name","age"});

		return beanWrapperFieldExtractor;
	}
	

}
